 /blog/archive/
/blog/archive/
 
          
          
              Rust default function parameters and Clap-rs argument YAMLs
Being new to Rust and coming from dramatically different languages naturally I searched last night for how to handle default function parameters. I had thought that surely I was just missing some obscure little syntactical trick that would make them work, I was surprised when a handful of searches camme back with:
Rust doesn’t support default function arguments.
Ok. Took a little bit to digest. I actually slept on it and then it came to me this morning.
"I can just use a struct constructor, should be easy." - thoughts in my head
Cargo.toml
[dependencies]
clap = { git = "https://github.com/clap-rs/clap/", features = ["yaml"] }Yeah, I know. It’s the beta 1, hang with me.
main.rs
extern crate clap;
struct State {
    verbose: bool,
}
impl State {
    fn new() -> State {
        State {
            verbose: false,
        }
    }
}
fn main() {
    let mut state = State::new();
    use clap::{load_yaml, App};
    let yml = load_yaml!("cli.yml");
    let matches = App::from(yml).get_matches();
    
    if matches.is_present("verbose") {
        state.verbose = true;
    }
    something(state)
}
fn something(state: State) {
    println!("What’s our state? {:?}", state.verbose)
}NOTE: No need for the cfg attribute in the Clap 3.x-beta1
All this talk of default arguments made me forget the real hotness, arg definitions in YAML!
cli.yml
name: verbose_app
version: "0.1"
about: This does next to nothing except take verbose flag
author: gatewaynode <44749714+gatewaynode@users.noreply.github.com>
args:
    - verbose:
        short: v
        long: verbose
        takes_value: false